package com.blb.blb_erp.conf;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.blb.blb_erp.realm.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * Shiro配置
 */
@Configuration
public class ShiroConfig {

    //返回Realm
    @Bean
    public UserRealm myRealm(){
        UserRealm myRealm = new UserRealm();
        //设置密码匹配器
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("md5");
        md5.setHashIterations(10);
        myRealm.setCredentialsMatcher(md5);
        //关闭缓存
        myRealm.setCachingEnabled(false);
        return myRealm;
    }

    //创建RememberMe管理器
    public CookieRememberMeManager rememberMeManager(){
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
        SimpleCookie rememberMe = new SimpleCookie("rememberMe");
        //单位是秒 过期时间
        rememberMe.setMaxAge(60 * 10);
        rememberMeManager.setCookie(rememberMe);
        return rememberMeManager;
    }

    //返回面向Web开发的安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager sm = new DefaultWebSecurityManager();
        //设置自定义Realm
        sm.setRealm(myRealm());
        //设置RememberMe
        sm.setRememberMeManager(rememberMeManager());
        return sm;
    }

    //返回Shiro过滤器链定义
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        //定义过滤器链key为url，value为anon不验证，authc验证
        //anon在前，authc在后，需要使用LinkedHashMap保留顺序
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("/pages/login22.html","anon");
        map.put("/user/login","anon");
        map.put("/static/**","anon");
        map.put("/**/*.css","anon");
        map.put("/**/*.js","anon");
        map.put("/**/*.jpg","anon");
        map.put("/**","user");
        chainDefinition.addPathDefinitions(map);
        return chainDefinition;
    }

    //启动thymeleaf的shiro标签
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

}
